package com.stylefeng.guns.rest.modular.wz.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.persistence.dao.PfFinanceRecordMapper;
import com.stylefeng.guns.rest.common.persistence.dao.WzUserFinanceRecordMapper;
import com.stylefeng.guns.rest.common.persistence.dao.WzUserMapper;
import com.stylefeng.guns.rest.common.persistence.model.PfFinanceRecord;
import com.stylefeng.guns.rest.common.persistence.model.WzUser;
import com.stylefeng.guns.rest.common.persistence.model.WzUserFinanceRecord;
import com.stylefeng.guns.rest.common.util.ResponseUtils;
import com.stylefeng.guns.rest.enums.EnWzUserFinanceRecord;
import com.stylefeng.guns.rest.pay.ali.AlipayConfig;
import com.stylefeng.guns.rest.pay.ali.AlipayNotify;
import com.stylefeng.guns.rest.pay.wx.WxPrepay;
import com.stylefeng.guns.rest.pay.wx.util.ConstantUtil;
import com.stylefeng.guns.rest.pay.wx.util.PayCommonUtil;
import com.stylefeng.guns.rest.pay.wx.util.XMLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by ruiyifeng on 2017/10/27.
 * 支付模块
 */
@Controller
@RequestMapping("/wz/pay/")
public class PayController extends ApiBaseController {

    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private PfFinanceRecordMapper pfFinanceRecordMapper;
    @Autowired
    private WzFinanceService financeService;


    //支付宝回调
    @RequestMapping(value = "mobilePayNotify")
    public String alipayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOGGER.info("$$$$alipayNotify进入!");
        boolean r = false;
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            // 买家付款账号
            BigDecimal total_amount = new BigDecimal(params.get("total_amount"));
            //买家支付宝账号
            String buyerId = params.get("buyer_id");
            // 商户订单号
            String out_trade_no = params.get("out_trade_no");
            // 支付宝交易号
            String trade_no = params.get("trade_no");
            // 交易状态
            String trade_status = params.get("trade_status");
            LOGGER.info("----------------------->交易状态:" + trade_status);
            String extraParam = "";
            int offset = out_trade_no.indexOf("_");
            if(offset>-1){
                extraParam = out_trade_no.substring(offset+1);
                out_trade_no = out_trade_no.substring(0,offset);
            }
            // 获得支付信息
            boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, "utf-8", "RSA2");
            if (flag) {// 验证成功
                if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
                    // 支付成功后执行相关业务
                    LOGGER.info("订单编号:"+out_trade_no+";支付金额:"+total_amount);
                    afterPay(out_trade_no, trade_no,buyerId);
                    ResponseUtils.renderText(response, "success");
                    return "success";
                }
            } else {
                LOGGER.info("$$$$alipayNotify验证失败——商户订单号:" + out_trade_no + ";支付宝交易号:" + trade_no + ",交易状态:" + trade_status);
            }
        } catch (Exception e) {
            LOGGER.info("$$$$alipayNotify业务逻辑异常:" + e.getMessage(), e);
            ResponseUtils.renderText(response, "fail");
        }
        return null;
    }

    /**
     * 微信-APP支付回调、H5支付回调
     * @return
     */
    @RequestMapping("wxpayNotify")
    public String wxpayNotify(HttpServletRequest request, HttpServletResponse response){
        try{
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result  = new String(outSteam.toByteArray(),"utf-8");//获取微信调用我们notify_url的返回信息
            Map<String, String> map = XMLUtil.doXMLParse(result);
            SortedMap<String, String> params = new TreeMap<String, String>(map);
            params.put("key", ConstantUtil.APP_KEY);
            LOGGER.error("微信支付成功回调result: " + result);
            if (WxPrepay.isValiSign(params)) {
                String out_trade_no = map.get("out_trade_no");
                String trade_no = (String) params.get("transaction_id");
                String openid = (String) params.get("openid");
                if ("SUCCESS".equalsIgnoreCase(map.get("result_code").toString())) {
                    //业务处理
                    afterPay(out_trade_no,trade_no,openid);
                    response.getWriter().write(PayCommonUtil.newXML("SUCCESS", ""));
                }
            }else{
                LOGGER.error("wxPayNotify验签失败！");
            }
        }catch(Exception e){
            try {
                e.printStackTrace();
                System.out.println("SEND WX FAIL Message");
                response.getWriter().write(PayCommonUtil.newXML("FAIL", e.getMessage()));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 回调业务处理
     */
    public boolean afterPay(String out_trade_no,String trade_no,String buyerId){
        boolean r = false;
        WzUserFinanceRecord userFinanceRecord = userFinanceRecordMapper.selectById(Long.parseLong(out_trade_no));
        if(userFinanceRecord.getStatus() == EnWzUserFinanceRecord.STATUS_waitCheck.getIndex()){//状态:待处理

            //充值业务处理
            if(userFinanceRecord.getPayType() == EnWzUserFinanceRecord.TITLE_alipay_recharge.getIndex() || userFinanceRecord.getPayType() == EnWzUserFinanceRecord.TITLE_wexin_recharge.getIndex()){
                r = financeService.recharge(out_trade_no,trade_no,userFinanceRecord);
            }

            //拼单业务处理
            if(userFinanceRecord.getPayType() == EnWzUserFinanceRecord.TITLE_Merge_Order_Cash.getIndex()){
                r = financeService.mapMergeCallback(trade_no,userFinanceRecord,buyerId);
            }

            //返利业务处理
            if(userFinanceRecord.getPayType() == EnWzUserFinanceRecord.TITLE_Rebate_Order_Cash.getIndex()){
                r = financeService.userRebateCallback(trade_no,userFinanceRecord,buyerId);
            }

            //原价买券业务处理
            if(userFinanceRecord.getPayType() == EnWzUserFinanceRecord.TITLE_Coupon_Order_Cash.getIndex()){
                r = financeService.couponOrderCashCallback(trade_no,userFinanceRecord,buyerId);
            }
        }
        return r;
    }
}
